<template>
  <el-card :bordered="false" style="width: 99%;margin: +0.5% auto;">
    <div class="app-container" style="margin: -1%;">
      <div class="filter-container">
        用户名称：
        <el-input
          v-model="listQuery.dict_name"
          placeholder="请输入用户名"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
        />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          新增
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: auto"
        :header-cell-style="{background:'#F8F8F9',color:'#515A6E'}"
      >
        <el-table-column
          label="ID"
          align="center"
          width="80px"
        >
          <template slot-scope="{row}">
            <span>{{ row.user.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户账号" align="center" width="110px">
          <template slot-scope="{row}">
            <span>{{ row.user_auths.identifier }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户姓名" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_info.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="电话" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_info.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="QQ/微信" width="110px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_info.qq }}</span>
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_info.department }}</span>
          </template>
        </el-table-column>
        <el-table-column label="职务" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_info.title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户类型" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_auths.identify_type }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user.updated_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" icon="el-icon-edit" plain @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button
              v-if="row.status!='删除'"
              size="mini"
              type="danger"
              plain
              icon="el-icon-delete"
              @click="handleDelete(row,$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="listQuery.pagination.total>0"
        :total="listQuery.pagination.total"
        :page.sync="listQuery.pagination.page"
        :limit.sync="listQuery.pagination.limit"
        @pagination="getList"
      />
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="850px" class="el-dialog-style">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="90px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="用户名称" prop="name">
                <el-input
                  v-model="temp.user_auths.identifier"
                  placeholder="请输入用户名称"
                  class="filter-item"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户昵称" prop="nickname">
                <el-input
                  v-model="temp.user.nickname"
                  placeholder="请输入用户昵称"
                  class="filter-item"
                  style="width: 80%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="temp.user_auths.credential"
                  placeholder="请输入密码"
                  minlength="6"
                  show-password="true"
                  style="width: 80%"
                  type="password"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input v-model="temp.user_info.phone" placeholder="请输入手机号码" style="width: 80%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门">
                <el-input v-model="temp.user_info.department" placeholder="请选择部门" style="width: 80%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务">
                <el-input v-model="temp.user_info.title" placeholder="请选择职务" style="width: 80%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="QQ/微信">
                <el-input v-model="temp.user_info.qq" placeholder="请输入QQ号" style="width: 80%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户类型">
                <el-input v-model="temp.user_info.qq" placeholder="请选择用户类型" style="width: 80%" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            关闭
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import { fetchPv, userPagination, userRegister, userEdit } from '@/api/article'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(urgent) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[urgent]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      list: null,
      listLoading: true,
      temp: {
        user: {
          id: 0,
          nickname: null,
          avatar: null
        },
        user_auths: {
          identify_type: null,
          identifier: null,
          credential: null
        },
        user_info: {
          name: null,
          qq: null,
          phone: null,
          title: null,
          department: null
        }
      },
      listQuery: {
        page: 1,
        limit: 20,
        user: {
          id: null,
          nickname: null,
          avatar: null,
          updated_time: ''
        },
        user_auths: {
          user_id: null,
          identify_type: null,
          identifier: null,
          credential: null
        },
        user_info: {
          name: null,
          qq: null,
          phone: null,
          title: null,
          department: null
        },
        pagination: {
          current: 0,
          limit: 10,
          total: 0,
          pages: 0,
          condition: null,
          page_info: {
            since_id: 0,
            max_id: 0
          },
          updated_time: undefined
        }
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '请填写用户名称', trigger: 'blur' }],
        nickname: [{ required: true, message: '请填写用户昵称', trigger: 'blur' }],
        credential: [{ required: true, message: '请填写密码', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写手机号', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      userPagination(this.listQuery).then(response => {
        this.list = response.data.user
        this.total = response.pagination.total
        this.listQuery.pagination.pages = response.pagination.current
        this.listQuery.pagination = response.pagination
        // console.log(this.listQuery.user.avatar)
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 100)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '工单完成',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        user: {
          id: 0,
          nickname: null,
          avatar: null
        },
        user_auths: {
          identify_type: null,
          identifier: null,
          credential: null
        },
        user_info: {
          name: null,
          qq: null,
          phone: null,
          title: null,
          department: null
        }
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          this.temp.author = 'vue-element-admin'
          userRegister(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '创建工单成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.temp = Object.assign({}, row) // copy obj
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          userEdit(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '编辑用户信息成功！',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: '删除工单成功！',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>
.el-dialog-style .el-dialog__header {
  border-bottom: 1px solid #e8eaec;
}

.el-drawer-style .el-drawer__header {
  border-bottom: 1px solid #e8eaec;
}

.el-table__header th {
  height: 30px;
}
</style>
